package com.lt.flashcard.view;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.hibernate.exception.ConstraintViolationException;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.Path;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Include;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.lt.flashcard.model.entity.Role;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class AdminCreateUsersCtrl extends SelectorComposer<Component> {

	private static final long serialVersionUID = 1L;
	
	@Wire("#popupcreateuser")
	private Window win;
	@Wire
	Textbox createusername;
	@Wire
	Textbox createemail;
	@Wire
	Textbox createpassword;
	@Wire
	Textbox createre_pass;
	@Wire
	Listbox listrolename;
	@Wire(".chkRole")
	private List<Checkbox> chkRole;

	@Wire
	private
	Include ctnUserlist;

	private List<Role> roleList = null;
	private User user = null;
	
	@Override
	public ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo) {
		Object user = Executions.getCurrent().getArg().get("user");
		this.user = (User) user;
		UserService usrv = Repository.getInstance().getUserService();
		roleList = usrv.getRoles();
		return super.doBeforeCompose(page, parent, compInfo);
	}
	
	public Include getCtnUserlist() {
		return ctnUserlist;
	}

	public void setCtnUserlist(Include ctnUserlist) {
		this.ctnUserlist = ctnUserlist;
	}
	
	@Listen("onClick=#btnClose")
	public void doClose() {
		((Window) getWindowComp()).detach();
//		if(getUser() == null){
//			createusername.setRawValue(null);
//			createemail.setRawValue(null);
//		}
//		createpassword.setRawValue(null);
//		createre_pass.setRawValue(null);
//		((Window) getWindowComp()).setVisible(false);
	}
	
	@Listen("onClick=#btnCreateUser")
	public void doCreate() {
		UserService usrv = Repository.getInstance().getUserService();
		Component com = Path.getComponent("//admin_user_page/ctnAdminUserpage");
		AdminUsersPageCtrl ctrl = (AdminUsersPageCtrl) com.getAttribute("$composer");
		Collection<Role> roles = new ArrayList<Role>();
		try {
			if(!createpassword.getValue().equals(createre_pass.getValue())) {
				throw new WrongValueException(createre_pass, "password doesn't match");
			}
			User user = new User(createusername.getValue(),createpassword.getValue(),createemail.getValue());
			for(Checkbox chk : getChkRole()) {
				if(chk.isChecked())
					roles.add(usrv.findRoleByname(chk.getLabel()));
			}
			user.getRoles().addAll(roles);
			usrv.save(user);
			ctrl.doFilter();
			((Window) getWindowComp()).detach();
		}
		catch (ConstraintViolationException e) {
			throw new ConstraintViolationException(e.getMessage(),e.getSQLException(),e.getConstraintName());
		}
		
	}
	
	@Listen("onClick=#btnSaveUser")
	public void doSave() {
		UserService usrv = Repository.getInstance().getUserService();
		Component com = Path.getComponent("//admin_user_page/ctnAdminUserpage");
		AdminUsersPageCtrl ctrl = (AdminUsersPageCtrl) com.getAttribute("$composer");
		Set<Role> roles = new HashSet<Role>();
		for(Checkbox chk : getChkRole()) {
			if(chk.isChecked())
				roles.add(usrv.findRoleByname(chk.getLabel()));
		}
		user.getRoles().clear();
		user.getRoles().addAll(roles);
		try{
			if(!createpassword.getValue().equals(createre_pass.getValue())) {
				throw new WrongValueException(createre_pass, "password doesn't match");
			}
			Sha256Hash hash = new Sha256Hash(createpassword.getValue(), null, 1024);
			user.setPassword(hash.toBase64());
			usrv.save(user);
			ctrl.doFilter();
			((Window) getWindowComp()).detach();
		}
		catch (Exception e) {
			Messagebox.show(e.getMessage());
		}
		
	}

	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}

	public Window getWin() {
		return win;
	}

	public void setWin(Window win) {
		this.win = win;
	}

	public List<Checkbox> getChkRole() {
		return chkRole;
	}

	public void setChkRole(List<Checkbox> chkRole) {
		this.chkRole = chkRole;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public Component getWindowComp(){
		return this.getSelf();
	}
}
